package com.seari.main;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.seari.bean.BaseTaskBean;
import com.seari.monitor.MonitorBootstrap;
import com.seari.service.BaseTaskService;
import com.seari.utils.DynamicCronTasks;
import com.seari.utils.LoadPropertiesUtils;
import com.seari.utils.SpringContextUtil;
import com.seari.web.controller.BaseTaskController;


@Component
@Order(value = 1)
public class BaseTaskStarter implements ApplicationRunner {
	public static ExecutorService service = Executors.newCachedThreadPool();
	private Logger logger = LoggerFactory.getLogger(BaseTaskStarter.class);
	public static Map<Runnable, String> cronTasks = new HashMap<Runnable, String>();
	public static Map<String, String> beanTaskMap = new HashMap<String, String>();

	@Autowired
	private BaseTaskService baseTaskService;

	@Autowired
	private DynamicCronTasks dynamicCronTasks;
	
	@Autowired
	private MonitorBootstrap monitorBootstrap;
	
	

	@Override
	public void run(ApplicationArguments arg0) throws Exception {
		init();
		restartContainer();
//		monitorBootstrap.initMonitorContainer();
	}

	public synchronized void restartContainer() {
		List<BaseTaskBean> tasks = baseTaskService.getBaseTask();
		for (BaseTaskBean baseTaskBean : tasks) {
			TaskRunner taskRunner = new TaskRunner(baseTaskBean);
			cronTasks.put(taskRunner, baseTaskBean.getRestartCycle());
		}
		dynamicCronTasks.schedulerTasks(cronTasks);
		cronTasks.clear();
		
	}


	private void init()
	{
		try
		{
			LoadPropertiesUtils.loadInfos();
			//从配置文件获取脚本根目录，默认为D盘BAT文件夹
			BaseTaskController.PATH = LoadPropertiesUtils.properties.getProperty("BAT_BASE_PATH", "D:/bat/");
		} catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
}
